# Copyright (c) 2017 Presto Labs Pte. Ltd.
# Author: xguo

from typing import List, Union
from tornado import gen
import json

from coin.exchange.huobi.ws.subscriber import HuobiSubscriberBase, TopicPatterns


class HuobiFuturesSubscriber(HuobiSubscriberBase):
  def __init__(self,
               queue,
               group_id: str,
               worker_id: str,
               symbol: Union[List[str], str],
               close_callback=None,
               logger=None):
    self._topics = TopicPatterns(
        trade='huobi_ws_futures_trade',
        depth='huobi_ws_futures_depth',
        delta_depth='huobi_ws_futures_delta_depth',
        topic_event='huobi_ws_futures_topic_event',
    )
    super().__init__(queue, group_id, worker_id, symbol, close_callback, logger)
    self._register_url('wss://www.hbdm.com/ws')

  @gen.coroutine
  def _send_subscribe_request(self):
    for symbol in self._symbol:
      self._logger.debug('Subscribing %s' % symbol)
      # Start from 20191107, use step6 which is 20 levels, instead of full book.
      yield self._ws.write_message(
          json.dumps({
              'sub': 'market.%s.depth.step6' % symbol, 'id': '%s.depth' % symbol
          }))
      yield self._ws.write_message(
          json.dumps({
              'sub': 'market.%s.trade.detail' % symbol, 'id': '%s.trade' % symbol
          }))
      yield gen.sleep(0.5)  # Sleep 0.5 second before next request

    self._publish_topic_event('START')
    self._logger.info('Subscribe done')
